/**
 * 
 */
package de.tum.in.eist.poll.client.views.widgets.evaluations;

import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.visualization.client.AbstractDataTable;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart;
import com.google.gwt.visualization.client.visualizations.corechart.PieChart.PieOptions;

import de.tum.in.eist.poll.shared.beans.SingleChoiceAnswer;
import de.tum.in.eist.poll.shared.beans.SingleChoiceQuestion;

/**
 * EvaluationWidget for a singlechoice question
 * @author Sebastian Hofstetter
 *
 */
public class QuestionSingleChoiceEvaluationWidget extends QuestionEvaluationWidget{
	private PieChart pie;	// the pie diagram
	private SingleChoiceAnswer[] answers;	// the answers which will be presented
	private SingleChoiceQuestion question;	// the questions which will be evaluated
	
	private VerticalPanel evaluationPanel = new VerticalPanel();
	
	public QuestionSingleChoiceEvaluationWidget(SingleChoiceAnswer[] answers, SingleChoiceQuestion question) {
		this.answers = answers;
		this.question = question;
		
		// Show a notice if there are no answers yet to present
		if (answers == null || answers.length == 0) {
			Label questionLabel = new Label(question.getQuestionText());
			questionLabel.addStyleName("question");
			evaluationPanel.add(questionLabel);
			evaluationPanel.add(new Label("No answers submitted yet."));
		} else {
			// show a pie diagram
			pie = new PieChart(createTable(), createPieOptions());
			evaluationPanel.add(pie);
		}
		evaluationPanel.addStyleName("questionSingleChoiceEvaluationWidget");
		
		initWidget(evaluationPanel);
	}
	
	/**
	 * the options of the pie diagram
	 * @return
	 */
	private PieOptions createPieOptions() {
	    PieOptions pieOptions = PieOptions.create();
	    pieOptions.setWidth(400);
	    pieOptions.setHeight(240);
	    pieOptions.set3D(true);
	    pieOptions.setTitle(question.getQuestionText());
	    return pieOptions;
	  }

	/**
	 * creates the table of answers, in order to present them as a pie diagram
	 * @return
	 */
	  private AbstractDataTable createTable() {
	    DataTable data = DataTable.create();
	    // Columns choice and count
	    data.addColumn(ColumnType.STRING, "Choice");
	    data.addColumn(ColumnType.NUMBER, "Count");
	    
	    data.addRows(question.getChoices().length);
	    
	    int choicesCount[] = new int[question.getChoices().length];
	    for (SingleChoiceAnswer a : answers) {
	    	choicesCount[a.getChoice()]++;
	    }
	    
	    // fill the table with the answer
	    for (int i = 0; i<question.getChoices().length; i++) {
	    	data.setValue(i, 0, question.getChoices()[i]);
	    	data.setValue(i, 1, choicesCount[i]);
	    }
	    
	    return data;
	  }
}
